package com.zhouyu.service;

import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;
import org.springframework.core.convert.support.DefaultConversionService;

import java.util.Collections;
import java.util.Set;

/**
 * 类型转换器
 *
 * @author zhaojy
 * @date 2025/10/15-4:33 下午
 */
public class StringToUserConvertor implements ConditionalGenericConverter {
	@Override
	public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
		return sourceType.getType().equals(String.class) && targetType.getType().equals(User.class);
	}

	@Override
	public Set<ConvertiblePair> getConvertibleTypes() {
		return Collections.singleton(new ConvertiblePair(String.class, User.class));
	}

	@Override
	public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
		User user = new User();
		user.setName((String) source);
		return user;
	}

	/**
	 * 使用转换器
	 *
	 * @param args String[]
	 */
	public static void main(String[] args) {
		DefaultConversionService conversionService = new DefaultConversionService();
		conversionService.addConverter(new StringToUserConvertor());

		User userNew = conversionService.convert("convertName", User.class);
		System.out.println(userNew.getName());
	}
}
